package Utils

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Users struct {
	Username string `json:"username"`
	Passwrod string `json:"passwrod"`
	jwt.StandardClaims
}

//type CustomClaims struct {
//	Users
//	jwt.StandardClaims
//}

var Mysecret=[]byte("blog_jwt_key")

//创建token
func GenToken(username string,password string)(string,error){
	//设置token有效时间
	nowTime:=time.Now()
	expireTime:=nowTime.Add(3*time.Hour)
	claim:=&Users{
		Username: username,
		Passwrod: password,
		StandardClaims:jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //3小时
			IssuedAt: nowTime.Unix(),
			Issuer:    "xx",
			Subject: "userToken", //签名主题
		},
	}
	token:=jwt.NewWithClaims(jwt.SigningMethodHS256,claim)
	return token.SignedString(Mysecret)
}

//解析token
func ParseToken(tokenStr string)(*Users,error){
	token,err:=jwt.ParseWithClaims(tokenStr,&Users{}, func(token *jwt.Token) (interface{}, error) {
		return Mysecret,nil
	})
	if err!=nil{
		fmt.Println("解析token异常:",err)
		return nil, err
	}
	if claims,ok:=token.Claims.(*Users);ok&&token.Valid{
		return claims, nil
	}
	return nil, errors.New("invalid token")
}

// 刷新 Token
//func RefreshToken(tokenStr string) (string, error) {
//	jwt.TimeFunc = func() time.Time {
//		return time.Unix(0, 0)
//	}
//
//	token, err := jwt.ParseWithClaims(tokenStr, &Users{}, func(token *jwt.Token) (interface{}, error) {
//		return Mysecret, nil
//	})
//	if err != nil {
//		return "", err
//	}
//	if claims, ok := token.Claims.(*Users); ok && token.Valid {
//		jwt.TimeFunc = time.Now
//		//claims.StandardClaims.ExpiresAt = jwt.At(time.Now().Add(time.Minute * 10))
//		return GenToken(claims.Users)
//	}
//	return "", errors.New("Cloudn't handle this token")
//}
